#!/bin/bash

set -e

show_help() {
    echo "usage: $(basename "$0") [-v <version>] [-o <output-dir>] [-g] [-h]"
    echo "       -v <version>       set version"
    echo "       -o <output-dir>    write source packages to this directory"
    echo "       -g                 use 'git describe' output as version string"
    echo "       -s                 use single source archive instead of no-vendor and"
    echo "                          only-vendor packages"
    echo "       -h                 show help"
    exit 1
}

if [ ! -e "packaging/$(basename "$0")" ]; then
    echo "must be executed at the top of srcdir"
    exit 1
fi

outdir=.
single=0

while getopts "v:o:gsh" arg; do
    case "$arg" in
        o)
            outdir="$OPTARG"
            ;;
        v)
            version="$OPTARG"
            ;;
        g)
            version="$(git describe | tr '-' '.')"
            ;;
        s)
            single=1
            ;;
        h|*)
            show_help
            ;;
    esac
done

if [ -z "$version" ]; then
    echo "error: version is unset"
    exit 1
fi

set -x

tmpdir=$(mktemp -d)
trap 'rm -rf "$tmpdir"' EXIT

if [[ "$single" == 0 ]]; then
    tar -cJf "$tmpdir"/snapd_"$version".no-vendor.tar.xz --exclude='vendor/*' --exclude='.git/*' --transform "s#^#snapd-$version/#" .
    tar -cJf "$tmpdir"/snapd_"$version".only-vendor.tar.xz --exclude='.git/*' --transform "s#^#snapd-$version/#" vendor

    mv "$tmpdir"/snapd_"$version".no-vendor.tar.xz "$outdir"/
    mv "$tmpdir"/snapd_"$version".only-vendor.tar.xz "$outdir"/
else
    tar -cJf "$tmpdir"/snapd_"$version".vendor.tar.xz --exclude='.git/*' --transform "s#^#snapd-$version/#" .
    mv "$tmpdir"/snapd_"$version".vendor.tar.xz "$outdir"/
fi
